import L from '@/libs/leaflet'
import SuperMap from '@/libs/supermap'
import '@/libs/plugins/leaflet-geoman/2.14.2/leaflet-geoman.min.js'
import '@/libs/iconfont/iconfont.js'
import * as turf from '@turf/turf'

import { getLayerManagerInfoApi, getAddManagerInfoApi, getMapModuleToolsApi } from '@/deps/api'
import { get, isEmpty, filter, each } from 'lodash'
import { sessionStorage } from '@/deps/utils'

// 地图对象
let mapObj = null
// 图层
let layers = {}
// 图层信息
let mapLayerInfos = {}
// 新增信息
let addLayerInfos = {}
// 工具栏信息
let mapModuleTools = {}

export function intToRGB(color) {
  var red = (color >> 16) & 0xff
  var green = (color >> 8) & 0xff
  var blue = color & 0xff
  return { red: red, green: green, blue: blue }
}
export function spColorToGeneral(color) {
  let supermapRGB = intToRGB(color)
  // 超图颜色转系统颜色
  let systemRGB = 'rgb(' + supermapRGB.blue + ', ' + supermapRGB.green + ', ' + supermapRGB.red + ')'
  return systemRGB
}

export function rgbToInt(r, g, b) {
  return (r << 16) + (g << 8) + b
}
// color为系统int类型颜色
export function generalIntToRGB(color) {
  let systemRGB = intToRGB(color)
  return 'rgb(' + systemRGB.red + ', ' + systemRGB.green + ', ' + systemRGB.blue + ')'
}

export function filterFeaturesInCircle(features, circle) {
  return filter(features, feature => {
    const coords = get(feature, 'geometry.coordinates', [])
    if (coords.length === 0) return false
    const firstPoint = L.latLng(coords[0][1], coords[0][0])
    const lastPoint = L.latLng(coords[coords.length - 1][1], coords[coords.length - 1][0])
    return circle.getBounds().contains(firstPoint) || circle.getBounds().contains(lastPoint)
  })
}
// 获取当前地图固定比例尺（格式为1:1000m）
export function getMapScale(mapObj) {
  const zoom = mapObj.getZoom()
  // 根据已知条件zoom=19时为1:1000，计算比例尺系数
  const scaleFactor = Math.pow(2, 19 - zoom)
  return 1000 * scaleFactor
}

export function checkGuideLines(currentLayer, allLayers) {
  const currentBounds = currentLayer.getBounds()
  const guides = { horizontal: [], vertical: [] }

  each(allLayers, layer => {
    if (layer === currentLayer) return
    const bounds = layer.getBounds()
    // 检查水平对齐
    if (Math.abs(bounds.getNorth() - currentBounds.getNorth()) < 5) {
      guides.horizontal.push(bounds.getNorth())
    }
    // 检查垂直对齐
    if (Math.abs(bounds.getEast() - currentBounds.getEast()) < 5) {
      guides.vertical.push(bounds.getEast())
    }
  })

  return guides
}
/** 构建平面无投影坐标对象参数
  origin - {Object} 原点
  bounds - {L.bounds|Array} 范围
  resolutions - {Array} 分辨率
***/
const bounds = {
  left: 498332.340136516,
  bottom: 3503534.60623486,
  right: 557181.700296097,
  top: 3539055.95819919,
  leftBottom: {
    x: 498332.340136516,
    y: 3503534.60623486
  },
  rightTop: {
    x: 557181.700296097,
    y: 3539055.95819919
  }
}
console.error(L.Proj)
// L.CRS({
//   bounds: L.bounds([bounds.left, bounds.bottom], [bounds.right, bounds.top]),
//   origin: L.point(bounds.left, bounds.top)
// })
var res = []
let scalesArr = get(sessionStorage('sysMapInfo'), '[0].mapScales', '').split(',')
// 25 需要改成 sessionStorage('sysMapInfo').mapScales ； 165664.43905455674 也需要改成数据库中设置的值
for (var i = 0; i < (scalesArr[1] || 25); i++) {
  res.push((scalesArr[0] || 165664.43905455674) / Math.pow(2, i))
}
const mapcrs = L.CRS.NonEarthCRS({
  bounds: L.bounds([bounds.left, bounds.bottom], [bounds.right, bounds.top]),
  origin: L.point(bounds.left, bounds.top),
  resolutions: res
})
let center = { x: 530940.5041341756, y: 3522854.3335092263 }
center = mapcrs.unproject(L.point(center.x, center.y))
var url = 'http://113.44.168.84:8090/iserver/services/map-jycatv/rest/maps/baseroadmap'

// 地图配置
let mapConfigs = {
  bounds,
  center,
  mapcrs,
  zoom: 20,
  maxZoom: res.length - 1,
  url,
  menuid: 680,
  rootClassType: 1
}

// 初始化地图
const mapInit = () => {
  mapObj = L.map('map', {
    crs: mapConfigs.mapcrs,
    zoom: mapConfigs.zoom,
    maxZoom: mapConfigs.maxZoom,
    center: mapConfigs.center,
    doubleClickZoom: false,
    preferCanvas: true
  })
  let layer = new L.supermap.tiledMapLayer(url, {
    maxZoom: res.length - 1,
    minZoom: 11,
    overlapDisplayed: true
  })
  layer.addTo(mapObj)
  layers['baseroadmap'] = layer
}

const featureService = new L.supermap.featureService('http://113.44.168.84:8090/iserver/services/data-jycatv/rest/data')
export const mapService = new SuperMap.MapService('http://113.44.168.84:8090/iserver/services/map-jycatv/rest/maps/baseroadmap')

// 获取地图配置
export const getMapConfigs = () => {
  return mapConfigs
}

// 设置地图配置
export const setMapConfigs = configs => {
  mapConfigs = Object.assign(mapConfigs, configs)
}

// 获取图层信息
export const getLayerManagerInfo = async () => {
  if (isEmpty(mapLayerInfos)) {
    try {
      const data = {
        menuid: mapConfigs.menuid,
        rootClassType: mapConfigs.rootClassType
      }
      const res = await getLayerManagerInfoApi(data)
      mapLayerInfos = res || []
      return mapLayerInfos
    } catch (err) {
      return mapLayerInfos
    }
  } else {
    return mapLayerInfos
  }
}

// 清除图层信息
export const clearLayerInfo = () => {
  mapLayerInfos = {}
}

// 获取新增信息
export const getAddManagerInfo = async () => {
  if (isEmpty(addLayerInfos)) {
    try {
      const data = {
        menuid: mapConfigs.menuid,
        rootClassType: mapConfigs.rootClassType
      }
      const res = await getAddManagerInfoApi(data)
      addLayerInfos = res || []
      return addLayerInfos
    } catch (err) {
      return addLayerInfos
    }
  } else {
    return addLayerInfos
  }
}

// 清除新增信息
export const clearMapModuleTool = () => {
  mapModuleTools = {}
}

// 获取新增信息
export const getMapModuleTool = async (webmoduleId = 60) => {
  try {
    const userData = sessionStorage('userData')
    const data = {
      menuid: mapConfigs.menuid,
      webmoduleId: webmoduleId,
      userName: userData.userName,
      systype: 0
    }
    const res = await getMapModuleToolsApi(data)
    return res || []
  } catch (err) {
    console.error('获取工具栏菜单失败:', err)
    return []
  }
}

// 清除新增信息
export const clearAddManagerInfo = () => {
  mapModuleTools = {}
}

// GeoJSON 配置生成器
const geoJSONOptions = {
  createFilter(MARK_SIDS, HAX_DATE_SID, layerObj) {
    return geoJsonFeature => {
      geoJsonFeature.properties.LAYERNAME = layerObj.LAYERNAME
      geoJsonFeature.properties.FEATURENAME = layerObj.FEATURENAME
      geoJsonFeature.properties.isCheck = layerObj.isCheck
      const SMID = get(geoJsonFeature, 'properties.SMID', null)
      const CHANGEDATE = get(geoJsonFeature, 'properties.CHANGEDATE', null)

      if (SMID) {
        MARK_SIDS.push(SMID)
        // 只在CHANGEDATE发生变化时才更新
        if (HAX_DATE_SID[SMID] !== CHANGEDATE) {
          const mark = document.querySelector(`.marker-icon-${SMID}`)
          mark && mark.remove()
          HAX_DATE_SID[SMID] = CHANGEDATE || 'noChangeDate'
        }
      }

      // 始终显示要素
      return true
    }
  },

  createPointToLayer(layerObj, nIcon = false, mapScale = 1, LAYER_SIZES) {
    let featureSize = LAYER_SIZES ? LAYER_SIZES[mapScale] : 30
    const featureCode = layerObj.FEATURECODE
    // featureSize = mapScale * featureSize
    return (feature, latlng) => {
      let rgbcolor = feature.properties.COLOR !== undefined ? spColorToGeneral(feature.properties.COLOR) : 'rgb(0,100,200)'
      const SMID = get(feature, 'properties.SMID', null)

      let divIcon = null
      if (nIcon) {
        const text = feature.properties.texts ? feature.properties.texts[0] : ''
        feature.properties.isCircle = true
        divIcon = L.divIcon({
          className: `marker-icon-${SMID} is-circle click-${layerObj.isCheck}`,
          html: `
            <div style="display:flex; flex-direction:column; align-items:center; width:${featureSize * 2}px;">
              <div style="background-color:${rgbcolor}; width:${featureSize}px; height:${featureSize}px; border-radius:50%; margin-bottom:2px;"></div>
              <div style="text-align:center; font-size:12px; white-space:nowrap;">${text}</div>
            </div>
          `,
          iconSize: [featureSize * 2, featureSize * 2],
          iconAnchor: [featureSize, featureSize / 2] // 将锚点设置在圆点的中心
        })
      } else {
        divIcon = L.divIcon({
          className: `marker-icon-${SMID} click-${layerObj.isCheck}`,
          html: `<div><svg class="icon" style="transform: rotate(${feature.properties.ANGLE || 0}deg);fill: ${rgbcolor};width:${featureSize}px; height:${featureSize}px;" aria-hidden="true"><use xlink:href="#icon-a-${featureCode}"></use></svg></div>`,
          iconSize: [featureSize, featureSize],
          iconAnchor: [featureSize / 2, featureSize / 2]
        })
      }
      return L.marker(latlng, {
        icon: divIcon,
        opacity: 1,
        rotationOrigin: 'center'
      })
    }
  },

  createStyle(layerObj) {
    const datasetType = layerObj.DATASETTYPE
    const rootFeatureColor = generalIntToRGB(layerObj.COLORINDEX)

    return feature => {
      if (datasetType === 1) {
        // 线数据样式
        return {
          color: feature.properties.COLOR ? generalIntToRGB(feature.properties.COLOR) : rootFeatureColor,
          weight: 3
        }
      } else if (datasetType === 2) {
        // 面数据样式
        return {
          color: rootFeatureColor,
          fillColor: rootFeatureColor,
          fillOpacity: 0.4,
          weight: 2
        }
      }
    }
  }
}

// 查询参数生成器
class QueryParamsBuilder {
  constructor() {
    // 绑定方法到实例
    this.createAttributeFilter = this.createAttributeFilter.bind(this)
    this.createBoundsParams = this.createBoundsParams.bind(this)
    this.createSQLParams = this.createSQLParams.bind(this)
    this.createGeometryParams = this.createGeometryParams.bind(this)
  }

  createBaseParams(layerObj) {
    return {
      name: `${layerObj.LAYERNAME}@${layerObj.ALIASNAME || 'capture'}`,
      datasetName: `${layerObj.ALIASNAME || 'capture'}:${layerObj.LAYERNAME}`,
      maxFeatures: 500
    }
  }

  createAttributeFilter(layerObj, curZoom, featureData) {
    let attributeFilter = ''
    const displayFilter = layerObj.DISPLAYFILTER
    const visibleScale = layerObj.VISIBLESCALE
    console.error(layerObj)
    console.error(featureData)
    // 处理显示过滤器
    if (displayFilter) {
      attributeFilter = displayFilter
      if (attributeFilter.includes('@')) {
        if (featureData && featureData.properties && featureData.properties.SMID) {
          attributeFilter = attributeFilter.replace('@', featureData.properties.SMID)
        }
      }
      if (attributeFilter.includes('#')) {
        attributeFilter = attributeFilter.replace('#', featureData.properties.C_SYS_ROOT_ID)
      }
      if (attributeFilter.includes('$')) {
        attributeFilter = attributeFilter.replace('$', '0')
      }
    }

    // 处理比例尺过滤器
    if (visibleScale) {
      // const scaleArr = visibleScale.split(';')
      // const [smallScale, bigScale] = scaleArr
      // const [smalla, smallb, smallc] = smallScale.split(',')
      // if (parseInt(smalla) < curZoom && curZoom <= parseInt(smallb)) {
      //   attributeFilter = attributeFilter ? `${attributeFilter} and ${smallc}` : smallc
      // }
      // const [biga, bigb, bigc] = bigScale.split(',')
      // if (parseInt(biga) < curZoom && curZoom <= parseInt(bigb)) {
      //   attributeFilter = attributeFilter ? `${attributeFilter} and ${bigc}` : bigc
      // }
    }
    return attributeFilter || 'SMID>0'
  }

  createBoundsParams(layerObj, bounds, attributeFilter) {
    const baseParams = this.createBaseParams(layerObj)

    return new SuperMap.GetFeaturesByBoundsParameters({
      bounds,
      queryParameter: {
        name: baseParams.name,
        attributeFilter
      },
      spatialQueryMode: 'INTERSECT',
      datasetNames: [baseParams.datasetName],
      fromIndex: 0,
      toIndex: baseParams.maxFeatures,
      maxFeatures: baseParams.maxFeatures
    })
  }

  createSQLParams(layerObj, attributeFilter) {
    const baseParams = this.createBaseParams(layerObj)

    return new SuperMap.GetFeaturesBySQLParameters({
      queryParameter: {
        name: baseParams.name,
        attributeFilter
      },
      datasetNames: [baseParams.datasetName],
      fromIndex: 0,
      toIndex: baseParams.maxFeatures
    })
  }

  createGeometryParams(layerObj, geometry, attributeFilter) {
    const baseParams = this.createBaseParams(layerObj)

    return new SuperMap.GetFeaturesByGeometryParameters({
      geometry,
      queryParameter: {
        name: baseParams.name,
        attributeFilter
      },
      datasetNames: [baseParams.datasetName],
      spatialQueryMode: 'INTERSECT',
      fromIndex: 0,
      toIndex: baseParams.maxFeatures
    })
  }
}

// 创建单例实例
const queryParamsBuilder = new QueryParamsBuilder()

// 导出配置生成器
export const { createFilter, createPointToLayer, createStyle } = geoJSONOptions

// 导出查询参数生成器实例及其方法
export const { createAttributeFilter, createBoundsParams, createSQLParams, createGeometryParams } = queryParamsBuilder

// 高亮样式配置
export const highlightStyle = {
  color: '#ff0000',
  weight: 4,
  opacity: 1,
  fillOpacity: 0.5,
  fillColor: '#ff0000' // 添加填充颜色
}

// 高亮管理器
class highlightManager {
  constructor() {
    this.highlightedLayers = new Map()
    this.originalStyles = new Map()
    this.highlightedLayerDatas = []
  }
  refresh(layers) {
    this.highlightedLayers = new Map()
    this.originalStyles = new Map()
    this.highlightedLayerDatas = []
    layers.forEach(({ layer, feature, layerObj }) => {
      this.highlight(layer, feature, layerObj)
    })
  }
  highlight(layer, feature, layerObj) {
    this.highlightedLayerDatas.push(feature.properties.SMID)
    const layerId = feature.properties.SMID

    console.log('Highlighting layer:', layerId, layer)

    // 如果已经高亮，先清除之前的高亮
    if (this.highlightedLayers.has(layerId)) {
      this.clearHighlight(layerId)
    }

    try {
      if (layer instanceof L.Marker) {
        // 点图层高亮
        const icon = layer.getIcon()
        if (!icon) {
          console.warn('No icon found for marker')
          return
        }

        // 保存原始图标配置
        this.originalStyles.set(layerId, {
          html: icon.options.html,
          iconSize: icon.options.iconSize,
          className: icon.options.className
        })

        // 创建高亮样式的图标
        const newHtml = icon.options.html
          .replace(/<div[^>]*>/, '<div style="transform: scale(1.2); transition: all 0.2s ease;">')
          .replace(/fill:\s*[^;"]+/g, 'fill: #ff0000')
          .replace(/color:\s*[^;"]+/g, 'color: #ff0000')

        const newIcon = L.divIcon({
          ...icon.options,
          html: newHtml,
          className: `${icon.options.className || ''} highlighted-marker`
        })

        layer.setIcon(newIcon)
        console.log('Applied marker highlight style with new icon')
      } else if (layer instanceof L.Path) {
        // 线或面图层高亮
        // 保存原始样式
        this.originalStyles.set(layerId, { ...layer.options })

        // 应用高亮样式
        layer.setStyle({
          color: '#ff0000',
          weight: 4,
          opacity: 1,
          fillOpacity: layer instanceof L.Polyline && !(layer instanceof L.Polygon) ? 0 : 0.5,
          fillColor: '#ff0000'
        })
        console.log('Applied path highlight style')
      }

      // 将图层置于顶层
      if (layer.bringToFront) {
        layer.bringToFront()
      }

      // 保存高亮图层
      this.highlightedLayers.set(layerId, layer)
      console.log('Added to highlighted layers:', this.highlightedLayers.size)
    } catch (error) {
      console.error('Error applying highlight:', error)
    }
  }

  clearHighlight(layerId) {
    const index = this.highlightedLayerDatas.findIndex(item => item === layerId)
    this.highlightedLayerDatas.splice(index, 1)
    const layer = this.highlightedLayers.get(layerId)
    const originalStyle = this.originalStyles.get(layerId)

    if (layer && originalStyle) {
      try {
        if (layer instanceof L.Marker) {
          // 恢复点图层原始样式
          const icon = L.divIcon(originalStyle)
          layer.setIcon(icon)
        } else if (layer instanceof L.Path) {
          // 恢复线或面图层原始样式
          layer.setStyle(originalStyle)
        }
      } catch (error) {
        console.error('Error clearing highlight:', error)
      }
    }
    console.error('Clearing highlight for layer:', layerId)
    this.highlightedLayers.delete(layerId)
    this.originalStyles.delete(layerId)
  }

  clearAllHighlights() {
    console.log('Clearing all highlights')
    for (const layerId of this.highlightedLayers.keys()) {
      this.clearHighlight(layerId)
    }
  }
}
// 导出高亮管理器
export { highlightManager }

// 框选管理器
class SelectionManager {
  constructor(map, featureGroup) {
    this.map = map
    this.featureGroup = featureGroup
    this.selectLayer = null
    this.startPoint = null
    this.isSelecting = false
    this.isRightToLeft = false
    this.selectedFeatures = []
    this.mouseDownTime = 0
    this.mouseMoveCount = 0
    this.isDragging = false
    this.enabled = false

    this.onMouseDown = this.onMouseDown.bind(this)
    this.onMouseMove = this.onMouseMove.bind(this)
    this.onMouseUp = this.onMouseUp.bind(this)
    this.onContextMenu = this.onContextMenu.bind(this)
  }

  enable() {
    if (this.enabled) return
    this.enabled = true
    this.map.dragging.disable()
    this.map.on('mousedown', this.onMouseDown)
    this.map.on('mousemove', this.onMouseMove)
    this.map.on('mouseup', this.onMouseUp)
    this.map.on('contextmenu', this.onContextMenu)
    this.map.getContainer().style.cursor = 'crosshair'
  }

  disable(clearSelection = false) {
    if (!this.enabled) return
    this.enabled = false
    this.map.off('mousedown', this.onMouseDown)
    this.map.off('mousemove', this.onMouseMove)
    this.map.off('mouseup', this.onMouseUp)
    this.map.off('contextmenu', this.onContextMenu)
    this.map.dragging.enable()
    this.map.getContainer().style.cursor = ''

    // 清除选择框
    if (this.selectLayer) {
      this.map.removeLayer(this.selectLayer)
      this.selectLayer = null
    }

    // 只在需要时清除选择
    if (clearSelection) {
      this.selectedFeatures = []
    }
  }

  onMouseDown(e) {
    if (!this.enabled) return
    this.startPoint = e.layerPoint
    this.isSelecting = true

    if (this.selectLayer) {
      this.map.removeLayer(this.selectLayer)
    }
    this.selectLayer = L.rectangle(
      [
        [0, 0],
        [0, 0]
      ],
      {
        color: '#ff0000',
        weight: 1,
        fillOpacity: 0.2
      }
    ).addTo(this.map)

    L.DomEvent.stop(e)
  }

  onMouseMove(e) {
    if (!this.enabled || !this.isSelecting) return

    const endPoint = e.layerPoint
    this.isRightToLeft = endPoint.x < this.startPoint.x

    const bounds = L.bounds(this.startPoint, endPoint)
    const northEast = this.map.layerPointToLatLng(bounds.getTopRight())
    const southWest = this.map.layerPointToLatLng(bounds.getBottomLeft())

    this.selectLayer.setBounds([southWest, northEast])
    this.selectLayer.setStyle({
      color: this.isRightToLeft ? '#0000ff' : '#ff0000'
    })

    L.DomEvent.stop(e)
  }

  onMouseUp(e) {
    if (!this.enabled || !this.isSelecting) return

    // 阻止事件冒泡，防止触发地图点击事件
    L.DomEvent.stop(e)
    L.DomEvent.stopPropagation(e)
    L.DomEvent.preventDefault(e)

    const endPoint = e.layerPoint
    const bounds = L.bounds(this.startPoint, endPoint)

    const selectBounds = L.latLngBounds(this.map.layerPointToLatLng(bounds.getBottomLeft()), this.map.layerPointToLatLng(bounds.getTopRight()))

    console.log('Selection bounds:', selectBounds.toBBoxString())
    console.log('Starting layer check, total layers:', this.featureGroup.getLayers().length)

    this.selectedFeatures = []

    this.featureGroup.eachLayer(layer => {
      console.log('Checking layer:', layer)
      if (layer.feature) {
        let isSelected = false

        try {
          if (layer instanceof L.Marker) {
            const latLng = layer.getLatLng()
            isSelected = selectBounds.contains(latLng)
            console.log('Marker check:', latLng, isSelected)
          } else if (layer instanceof L.Polyline) {
            const latLngs = layer.getLatLngs()
            if (this.isRightToLeft) {
              isSelected = latLngs.some(latLng => selectBounds.contains(latLng))
            } else {
              isSelected = latLngs.every(latLng => selectBounds.contains(latLng))
            }
          } else if (layer instanceof L.Polygon) {
            const layerBounds = layer.getBounds()
            if (this.isRightToLeft) {
              isSelected = selectBounds.intersects(layerBounds)
            } else {
              isSelected = selectBounds.contains(layerBounds)
            }
          }

          if (isSelected) {
            console.log('Selected feature:', layer.feature.properties)
            this.selectedFeatures.push(layer.feature)
            this.map.fire('feature:selected', {
              feature: layer.feature,
              layer: layer,
              selectionType: this.isRightToLeft ? 'intersects' : 'contains'
            })
          }
        } catch (error) {
          console.error('Error checking layer:', error)
        }
      }
    })

    console.log('Selection complete, features selected:', this.selectedFeatures.length)

    if (this.selectedFeatures.length > 0) {
      this.map.fire('selection:complete', {
        features: this.selectedFeatures,
        selectionType: this.isRightToLeft ? 'intersects' : 'contains'
      })
    }

    // 清除选择框
    if (this.selectLayer) {
      this.map.removeLayer(this.selectLayer)
      this.selectLayer = null
    }

    this.isSelecting = false
    this.startPoint = null
  }

  onContextMenu(e) {
    if (!this.enabled) return

    // 阻止默认右键菜单
    L.DomEvent.stop(e)
    L.DomEvent.preventDefault(e)

    // 触发自定义事件通知需要关闭框选
    this.map.fire('selection:cancel')
  }
}

// 导出创建工具的函数
export const createSelectionTool = (map, featureGroup) => {
  return new SelectionManager(map, featureGroup)
}

// 导出其他工具方法和对象
export { mapInit, mapObj, layers, featureService }

// 图层加载管理器
class LayerManager {
  constructor(map) {
    this.map = map
    this.geoLayers = {}
    this.dataFeatureGroup = L.featureGroup().addTo(map)
    this.currentFeatureData = null
    this.currentLayers = []
  }

  async loadMaps(layersAll = [], featureData = null) {
    this.currentFeatureData = featureData
    // 清除之前的图层
    this.clearLayers()

    if (layersAll.length > 0) {
      this.currentLayers = layersAll
      // 使用 Promise.all 等待所有图层加载完成
      await Promise.all(
        layersAll.map(async layer => {
          // 图层类别（0矢量data，1百度，2wms，3rest）
          if (layer.LAYERTYPE === 3) {
            let mapurl = layer.BACKGROUNDURL
            if (mapurl) {
              const mlayer = L.supermap
                .tiledMapLayer(mapurl, {
                  noWrap: true
                })
                .addTo(this.map)

              layer.layervar = mlayer
              this.geoLayers['' + layer.M_SYS_ROOT_ID] = mlayer
            }
          } else if (layer.LAYERTYPE === 0) {
            await this.queryFeatures(layer)
          } else {
            console.log('不支持的图层类型:', layer.LAYERTYPE)
          }
        })
      )
    } else {
      console.log('图层信息为空')
    }
  }

  clearLayers() {
    // 清除所有图层
    this.dataFeatureGroup.eachLayer(l => {
      this.dataFeatureGroup.removeLayer(l)
    })
    Object.values(this.geoLayers).forEach(layer => {
      if (layer && this.map.hasLayer(layer)) {
        this.map.removeLayer(layer)
      }
    })
    this.geoLayers = {}
    console.error('clearLayers', this.dataFeatureGroup._layers)
  }

  async queryFeatures(layerObj) {
    const curZoom = this.map.getZoom()

    // 使用现有的 queryParamsBuilder 创建查询参数，传入当前 featureData
    const attributeFilter = createAttributeFilter(layerObj, curZoom, this.currentFeatureData)
    const getFeatureParams = createSQLParams(layerObj, attributeFilter)

    // 将回调转换为 Promise
    return new Promise((resolve, reject) => {
      featureService.getFeaturesBySQL(getFeatureParams, serviceResult => {
        try {
          if (!serviceResult.result || !serviceResult.result.features) {
            console.log('未获取到图层数据')
            resolve()
            return
          }

          const features = serviceResult.result.features
          const datasetType = layerObj.DATASETTYPE
          features.features.forEach(feature => {
            feature.properties.LAYERNAME = layerObj.LAYERNAME
            feature.properties.FEATURENAME = layerObj.FEATURENAME
          })
          console.log('features', features)
          // 根据数据集类型处理图层
          if (datasetType < 3) {
            // 点、线、面要素，使用现有的 geoJSONOptions
            this.handleVectorLayer(features, layerObj, curZoom)
          } else if (datasetType === 3) {
            // 面标注
            this.handleAreaLabelLayer(features, layerObj, curZoom)
          } else if (datasetType === 4) {
            // 点标注
            this.handlePointLabelLayer(features, layerObj, curZoom)
          }
          resolve()
        } catch (error) {
          console.error('处理图层数据时出错:', error)
          reject(error)
        }
      })
    })
  }

  handleVectorLayer(features, layerObj, curZoom) {
    const mlayer = L.geoJSON(features, {
      onEachFeature: (feature, layer) => {
        if (!this.dataFeatureGroup.hasLayer(layer)) {
          this.dataFeatureGroup.addLayer(layer)
        }
      },
      style: feature => {
        const featureColor = feature.properties.COLOR
        const layerColor = layerObj.COLORINDEX
        let color
        if (featureColor || featureColor === 0) {
          color = generalIntToRGB(featureColor)
        } else if (layerColor || layerColor === 0) {
          color = generalIntToRGB(layerColor)
        } else {
          color = 'rgb(0,100,200)' // 默认颜色
        }

        if (layerObj.DATASETTYPE === 2) {
          let fillColor = feature.properties.FILLCOLOR ? feature.properties.FILLCOLOR : feature.properties.BRUSHCOLOR
          fillColor = fillColor ? generalIntToRGB(fillColor) : 'RGB(0,100,200)'
          // 面数据样式
          return {
            color: color,
            fillColor: fillColor,
            fillOpacity: 0.4,
            weight: Math.max(1, curZoom / 10) // 根据缩放级别调整线宽
          }
        } else {
          // 线数据样式
          return {
            color: color,
            weight: Math.max(2, curZoom / 8) // 根据缩放级别调整线宽
          }
        }
      },
      pointToLayer: createPointToLayer(layerObj, true)
    }).addTo(this.map)
  }

  handleAreaLabelLayer(features, layerObj, curZoom) {
    const labelShowVertical = layerObj.LABELSHOWVERTICAL === 0 ? 0 : 1
    const labelWidth = labelShowVertical === 0 ? 103 : 13
    const LABELFIELD = layerObj.LABELFIELD

    // 计算字体大小和缩放
    const { fontsize, fontsizeScal } = this.calculateFontParams(curZoom)

    // 转换面要素中心点
    const centerPoints = features.features
      .map(feature => {
        try {
          const center = turf.center(feature)
          center.id = feature.id
          center.properties = feature.properties
          return center
        } catch (e) {
          console.error('面转点失败:', e)
          return null
        }
      })
      .filter(point => point !== null)

    const mlayer = L.geoJSON(centerPoints, {
      snapIgnore: true,
      onEachFeature: (feature, layer) => {
        if (!this.dataFeatureGroup.hasLayer(layer)) {
          this.dataFeatureGroup.addLayer(layer)
        }
      },
      pointToLayer: (feature, latlng) => {
        const rgbcolor = feature.properties.COLOR ? spColorToGeneral(feature.properties.COLOR) : 'RGB(0,100,200)'

        const labelContent = LABELFIELD ? feature.properties[LABELFIELD] : feature.properties.NOTENAME || (feature.properties.texts && feature.properties.texts[0]) || ''

        const divIcon = L.divIcon({
          className: '',
          html: `<span style="display:inline-block;text-align:center;word-wrap:break-word;width:${labelWidth}px;font-size:${fontsize}px;-webkit-transform:scale(${fontsizeScal}) translateX(-50%);color:${rgbcolor}">${labelContent}</span>`,
          iconSize: [15, 15]
        })

        return L.marker(latlng, {
          icon: divIcon,
          rotationOrigin: 'center'
        })
      }
    }).addTo(this.map)
  }

  handlePointLabelLayer(features, layerObj, curZoom) {
    const labelShowVertical = layerObj.LABELSHOWVERTICAL === 0 ? 0 : 1
    let labelWidth = labelShowVertical === 0 ? 130 : 13
    const notoffsetx = typeof layerObj.NOTEOFFSETX === 'number' ? layerObj.NOTEOFFSETX : 0
    const notoffsety = typeof layerObj.NOTEOFFSETY === 'number' ? layerObj.NOTEOFFSETY : 10

    // 计算字体大小和缩放
    const { fontsize, fontsizeScal } = this.calculateFontParams(curZoom)

    const mlayer = L.geoJSON(features, {
      snapIgnore: true,
      onEachFeature: (feature, layer) => {
        if (!this.dataFeatureGroup.hasLayer(layer)) {
          this.dataFeatureGroup.addLayer(layer)
        }
      },
      pointToLayer: (feature, latlng) => {
        const rgbcolor = 'RGB(0,50,200)'
        const content = feature.properties.NOTENAME || (feature.properties.texts && feature.properties.texts[0]) || ''

        // 调整标签宽度
        if (content.length > 10 && labelShowVertical === 0) {
          labelWidth = content.length * 13
        }

        const divIcon = L.divIcon({
          className: '',
          html: `<span style="display:inline-block;word-wrap:break-word;width:${labelWidth}px;font-size:${fontsize}px;-webkit-transform:scale(${fontsizeScal});transform-origin:top left;color:${rgbcolor}">${content}</span>`,
          iconSize: [15, 15]
        })

        // 计算偏移后的位置
        const offsetLatLng = L.latLng(latlng.lat - notoffsety, latlng.lng - notoffsetx)

        return L.marker(offsetLatLng, {
          icon: divIcon,
          rotationOrigin: 'center'
        })
      }
    }).addTo(this.map)
  }

  calculateFontParams(curZoom) {
    let fontsize = 12
    let fontsizeScal = 1

    if (curZoom <= 1) {
      fontsizeScal = 0.75
    } else if (curZoom === 2) {
      fontsizeScal = 0.7
    } else if (curZoom === 3) {
      fontsizeScal = 0.8
    } else if (curZoom === 0) {
      fontsize = 0
      fontsizeScal = 0
    } else if (curZoom > 6) {
      fontsizeScal = 1
      fontsize = fontsize + curZoom * 2
    }

    return { fontsize, fontsizeScal }
  }
}

// 创建图层管理器实例
export const createLayerManager = map => {
  return new LayerManager(map)
}

/**
 * 处理工具栏菜单数据
 * @param {Array} menus 原始菜单数据
 * @param {Object} options 配置选项
 * @param {boolean} options.flat 是否扁平化child
 * @param {Array} options.excludeCommands 需要排除的commandName数组
 * @returns {Array} 处理后的菜单数据
 */
export function processToolbarMenus(menus, options = {}) {
  if (!Array.isArray(menus)) return []

  let { flat = false, excludeCommands = [] } = options
  excludeCommands = [...excludeCommands, 'cancleAction', 'redoAction']
  // 深度拷贝避免修改原始数据
  let result = JSON.parse(JSON.stringify(menus))

  // 过滤排除项
  result = result.filter(menu => !flat || (menu.child && menu.child.length > 0))

  // 如果需要扁平化child
  if (flat) {
    result = result.reduce((acc, menu) => {
      if (menu.child && Array.isArray(menu.child)) {
        acc.push(...menu.child)
      }
      return acc
    }, [])
  }
  console.error(result)
  result = result.filter(item => {
    if (item.child) {
      item.child = item.child.filter(childItem => !excludeCommands.includes(childItem.COMMANDNAME))
    }
    return !excludeCommands.includes(item.COMMANDNAME)
  })
  return result
}
